import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  message, 
  Popconfirm, 
  Tooltip, 
  Collapse,
  Typography,
  Row,
  Col,
  Statistic,
  Divider,
  Spin
} from 'antd';
import { 
  DeleteOutlined, 
  ReloadOutlined, 
  EyeOutlined, 
  FileTextOutlined,
  UserOutlined,
  TrophyOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import CodeMirror from '@uiw/react-codemirror';
import { python } from '@codemirror/lang-python';
import { cpp } from '@codemirror/lang-cpp';
import { java } from '@codemirror/lang-java';
import { javascript } from '@codemirror/lang-javascript';
import { contestService } from '@/services/contestService';
import { ContestUserSubmission, ContestSubmission } from '@/types/contest';
import { Contest, ContestRuleType } from '@/types/contest';
import dayjs from 'dayjs';

const { Panel } = Collapse;
const { Text, Title } = Typography;

// 根据语言获取CodeMirror扩展
const getLanguageExtension = (language: string) => {
  const lang = language.toLowerCase();
  if (lang.includes('python')) return python();
  if (lang.includes('cpp') || lang.includes('c++')) return cpp();
  if (lang.includes('java')) return java();
  if (lang.includes('javascript') || lang.includes('js')) return javascript();
  return python(); // 默认使用Python
};

// 评测结果映射
const JUDGE_STATUS_MAP: { [key: number]: { text: string; color: string } } = {
  0: { text: 'Accepted', color: 'success' },
  1: { text: 'Wrong Answer', color: 'error' },
  2: { text: 'Judging', color: 'processing' },
  3: { text: 'Compile Error', color: 'warning' },
  4: { text: 'Time Limit Exceeded', color: 'error' },
  5: { text: 'Memory Limit Exceeded', color: 'error' },
  6: { text: 'Pending', color: 'default' },
  7: { text: 'Runtime Error', color: 'error' },
  8: { text: 'System Error', color: 'error' },
};

const ContestReview: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [contest, setContest] = useState<Contest | null>(null);
  const [submissions, setSubmissions] = useState<ContestUserSubmission[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [codeModalVisible, setCodeModalVisible] = useState(false);
  const [selectedSubmission, setSelectedSubmission] = useState<ContestSubmission | null>(null);
  const [operating, setOperating] = useState(false);

  // 获取比赛信息
  const fetchContest = async () => {
    if (!id) return;
    try {
      const response = await contestService.getContest(parseInt(id));
      setContest(response.data.data);
    } catch (error) {
      message.error('获取比赛信息失败');
    }
  };

  // 获取提交列表
  const fetchSubmissions = async (page = 1, pageSize = 10) => {
    if (!id) return;
    try {
      setLoading(true);
      const response = await contestService.getContestSubmissions(parseInt(id), {
        page,
        page_size: pageSize
      });
      
      if (response.data?.code === 200) {
        const data = response.data.data;
        console.log('API返回的数据:', data); // 调试信息
        // 根据实际API返回格式，data是直接的数组
        setSubmissions(data || []);
        // 由于API没有返回分页信息，我们使用简单的分页
        setPagination({
          current: page,
          pageSize: pageSize,
          total: data?.length || 0,
        });
      }
    } catch (error) {
      console.error('获取提交列表失败:', error);
      message.error('获取提交列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContest();
    fetchSubmissions();
  }, [id]);

  // 删除提交
  const handleDeleteSubmission = async (submissionId: string) => {
    try {
      setOperating(true);
      await contestService.deleteSubmission(submissionId);
      message.success('删除成功');
      fetchSubmissions(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('删除提交失败:', error);
      message.error('删除失败');
    } finally {
      setOperating(false);
    }
  };

  // 重新评测提交
  const handleRejudgeSubmission = async (submissionId: string) => {
    try {
      setOperating(true);
      await contestService.rejudgeSubmission(submissionId);
      message.success('重新评测任务已发送');
      fetchSubmissions(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('重新评测失败:', error);
      message.error('重新评测失败');
    } finally {
      setOperating(false);
    }
  };

  // 查看代码
  const handleViewCode = (submission: ContestSubmission) => {
    setSelectedSubmission(submission);
    setCodeModalVisible(true);
  };

  // 获取评测状态标签
  const getJudgeStatusTag = (result: number) => {
    const status = JUDGE_STATUS_MAP[result] || { text: 'Unknown', color: 'default' };
    return <Tag color={status.color}>{status.text}</Tag>;
  };

  // 格式化时间
  const formatTime = (seconds: number) => {
    if (seconds === undefined || seconds === null) return '-';
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    if (hours > 0) {
      return `${hours}小时${minutes}分钟`;
    }
    return `${minutes}分钟`;
  };

  if (!contest) {
    return <Spin size="large" />;
  }

  return (
    <div>
      <Card>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Title level={3} style={{ margin: 0 }}>
              <FileTextOutlined /> {contest.title} - 比赛批阅
            </Title>
            <div style={{ marginTop: 8, color: '#666', fontSize: '14px' }}>
              <Space size="large">
                <span>
                  <UserOutlined style={{ marginRight: 4 }} />
                  参赛人数: {submissions.length}
                </span>
                <span>
                  <TrophyOutlined style={{ marginRight: 4 }} />
                  类型: {contest.rule_type}
                </span>
                <span>
                  <ClockCircleOutlined style={{ marginRight: 4 }} />
                  时间: {dayjs(contest.start_time).format('MM-DD HH:mm')} ~ {dayjs(contest.end_time).format('MM-DD HH:mm')}
                </span>
              </Space>
            </div>
          </Col>
          <Col>
            <Button onClick={() => navigate('/admin/contest/list')}>
              返回列表
            </Button>
          </Col>
        </Row>
      </Card>

      <Card title="参赛选手提交详情" loading={loading}>
        {submissions.map((userSubmission) => (
          <Card 
            key={userSubmission.user_id} 
            style={{ marginBottom: 16 }}
            title={
              <Space>
                <UserOutlined />
                <Text strong>{userSubmission.username}</Text>
                {userSubmission.real_name && (
                  <Text type="secondary">({userSubmission.real_name})</Text>
                )}
              </Space>
            }
            extra={
              <Space>
                <Statistic 
                  title="总分" 
                  value={userSubmission.total_score} 
                  prefix={<TrophyOutlined />}
                  valueStyle={{ fontSize: '16px' }}
                />
                {contest?.rule_type === 'ACM' && (
                  <Statistic 
                    title="AC数" 
                    value={userSubmission.accepted_number} 
                    valueStyle={{ fontSize: '16px' }}
                  />
                )}
                <Statistic 
                  title="提交数" 
                  value={userSubmission.submission_number} 
                  valueStyle={{ fontSize: '16px' }}
                />
                {contest?.rule_type === 'ACM' && (
                  <Statistic 
                    title="用时" 
                    value={formatTime(userSubmission.total_time)} 
                    prefix={<ClockCircleOutlined />}
                    valueStyle={{ fontSize: '16px' }}
                  />
                )}
              </Space>
            }
          >
            <Collapse ghost>
              {userSubmission.problems.map((problem) => (
                <Panel 
                  key={problem.problem_id} 
                  header={
                    <Space>
                      <FileTextOutlined />
                      <Text strong>{problem.problem_title}</Text>
                      <Text type="secondary">(ID: {problem.problem_id})</Text>
                      <Tag color="blue">{problem.submissions.length} 次提交</Tag>
                    </Space>
                  }
                >
                  {problem.submissions.length > 0 ? (
                    <Table
                      columns={[
                        {
                          title: '提交时间',
                          dataIndex: 'create_time',
                          key: 'create_time',
                          width: 180,
                          render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
                        },
                        {
                          title: '语言',
                          dataIndex: 'language',
                          key: 'language',
                          width: 100,
                        },
                        {
                          title: '结果',
                          dataIndex: 'result',
                          key: 'result',
                          width: 120,
                          render: (result: number) => getJudgeStatusTag(result),
                        },
                        {
                          title: '得分',
                          dataIndex: 'statistic_info',
                          key: 'score',
                          width: 80,
                          render: (info: any) => info?.score || '-',
                        },
                        {
                          title: '用时',
                          dataIndex: 'statistic_info',
                          key: 'time',
                          width: 80,
                          render: (info: any) => info?.time_cost ? `${info.time_cost}ms` : '-',
                        },
                        {
                          title: '内存',
                          dataIndex: 'statistic_info',
                          key: 'memory',
                          width: 80,
                          render: (info: any) => info?.memory_cost ? `${info.memory_cost}KB` : '-',
                        },
                        {
                          title: '操作',
                          key: 'action',
                          width: 200,
                          render: (_: any, record: ContestSubmission) => (
                            <Space size="small">
                              <Tooltip title="查看代码">
                                <Button 
                                  type="link" 
                                  size="small" 
                                  icon={<EyeOutlined />}
                                  onClick={() => handleViewCode(record)}
                                >
                                  代码
                                </Button>
                              </Tooltip>
                              <Tooltip title="重新评测">
                                <Button 
                                  type="link" 
                                  size="small" 
                                  icon={<ReloadOutlined />}
                                  onClick={() => handleRejudgeSubmission(record.id)}
                                  disabled={record.result === 2} // 评测中禁用
                                >
                                  重评
                                </Button>
                              </Tooltip>
                              <Popconfirm
                                title="确定要删除这个提交吗？"
                                onConfirm={() => handleDeleteSubmission(record.id)}
                              >
                                <Tooltip title="删除提交">
                                  <Button 
                                    type="link" 
                                    size="small" 
                                    danger 
                                    icon={<DeleteOutlined />}
                                  >
                                    删除
                                  </Button>
                                </Tooltip>
                              </Popconfirm>
                            </Space>
                          ),
                        },
                      ]}
                      dataSource={problem.submissions}
                      rowKey="id"
                      size="small"
                      pagination={false}
                      scroll={{ x: 800 }}
                    />
                  ) : (
                    <Text type="secondary">暂无提交</Text>
                  )}
                </Panel>
              ))}
            </Collapse>
          </Card>
        ))}
        
        {/* 由于API没有分页，暂时隐藏分页控件 */}
        
        {submissions.length === 0 && (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Text type="secondary">暂无参赛选手提交</Text>
          </div>
        )}
      </Card>

      {/* 代码查看模态框 */}
      <Modal
        title={
          <div style={{
            backgroundColor: 'rgba(240, 242, 247, 0.8)',
            margin: '-24px -24px 0 -24px',
            padding: '16px 24px',
            borderBottom: '1px solid rgba(0, 0, 0, 0.06)',
            fontWeight: 600,
            fontSize: '16px'
          }}>
            查看代码
          </div>
        }
        open={codeModalVisible}
        onCancel={() => setCodeModalVisible(false)}
        footer={null}
        width="80%"
        style={{ 
          backdropFilter: 'blur(20px)',
          backgroundColor: 'rgba(255, 255, 255, 0.8)',
          borderRadius: '12px',
          overflow: 'hidden',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          border: '1px solid rgba(255, 255, 255, 0.2)',
          padding: '0px',
        }}
        destroyOnClose
      >
        {selectedSubmission && (
          <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
            {/* 信息栏 */}
            <div style={{ 
              backgroundColor: 'rgba(250, 251, 252, 0.9)', 
              padding: '16px 24px', 
              borderBottom: '1px solid rgba(0, 0, 0, 0.06)',
              flexShrink: 0
            }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Text strong>语言: </Text>
                  <Text>{selectedSubmission.language}</Text>
                </Col>
                <Col span={8}>
                  <Text strong>提交时间: </Text>
                  <Text>{dayjs(selectedSubmission.create_time).format('YYYY-MM-DD HH:mm:ss')}</Text>
                </Col>
                <Col span={8}>
                  <Text strong>状态: </Text>
                  {getJudgeStatusTag(selectedSubmission.result)}
                </Col>
              </Row>
            </div>
            
            {/* 代码编辑器 */}
            <div style={{ 
              flex: 1, 
              minHeight: 0,
              maxHeight: '60vh',
              overflow: 'hidden'
            }}>
              <CodeMirror
                value={selectedSubmission.code}
                height="60vh"
                theme="light"
                editable={false}
                extensions={[getLanguageExtension(selectedSubmission.language)]}
              />
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ContestReview;
